package com.easylinkin.linkappapi.lobar.util;

import com.alibaba.fastjson.JSONObject;
import com.easylinkin.linkappapi.openapi.util.HttpClientUtil;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.Date;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

/**
 * @author xiaoyang
 * @version 1.0
 * @date 2022/06/22
 * @description 工地卫士api
 */
@Slf4j
@Component
public class BladeGuardApi {


  @Value("${bladeGuard.apiUrl}")
  public String apiUrl;
  @Value("${bladeGuard.username}")
  private String username;
  @Value("${bladeGuard.password}")
  private String password;
  @Value("${bladeGuard.tenantId}")
  private String tenantId;

  /**
   * 获取Token
   */
  public String getAccessToken() {
    String params = String
        .format("username=%s&password=%s&tenantId=%s&grant_type=password&scope=all&type=account",
            username,
            password, tenantId);
    HttpPost httpPost = new HttpPost(apiUrl + "/blade-auth//oauth/token");
    //添加请求头
    httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
    //设置接收形式
    httpPost.setHeader("Accept", "application/json");
    //设置租户id
    httpPost.setHeader("Tenant-Id", tenantId);
    //设置授权
    httpPost.setHeader("Authorization", "Basic c2FiZXI6c2FiZXJfc2VjcmV0");
    //创建登录实体
    httpPost.setEntity(new StringEntity(params, Charset.forName("UTF-8")));
    log.info("BladeGuardApi getAccessToken req:{}", httpPost);
    String str = HttpClientUtil.doPost(httpPost);
    log.info("BladeGuardApi getAccessToken res:" + str);
    JSONObject result = JSONObject.parseObject(str);
    if (null == result || StringUtils.isEmpty(result.getString("access_token"))) {
      return "";
    }
    return result.getString("access_token");
  }

  /**
   * 代打卡
   *
   * @param userId 工地卫士 userId
   * @param projectID 工地卫士 projectID
   * @param weidu 闸机 维度
   * @param jingdu 闸机 经度
   * @param idCard 闸机刷脸-身份证
   * @param name 闸机刷脸-身份证姓名
   * @param identityName 身份角色 例：建筑工人
   * @param projectName 项目名称
   * @param projectAddress 项目地址
   * @param date 闸机刷脸时间
   */
  public Boolean scanHealthCode(String userId, String projectID, String weidu, String jingdu,
      String idCard, String name, String identityName, String phone,
      String projectName, String projectAddress,Date date) {
    log.info(
        "scanHealthCode userId: {}, projectID: {}, projectName: {}, projectAddress: {}, weidu: {}, jingdu: {}, idCard: {}, name: {}, identityName: {}, phone: {}",
        userId, projectID, projectName, projectAddress, weidu, jingdu, idCard, name, identityName, phone);
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    String scanTime = dateFormat.format(date);
    StringBuilder params = new StringBuilder();
    // 闸机信息
    try {
      params.append("userId=").append(userId).append("&")
          .append("projectId=").append(projectID).append("&")
          .append("projectName=").append(URLEncoder.encode(projectName,"utf-8")).append("&")
          .append("projectAddress=").append(URLEncoder.encode(projectAddress,"utf-8")).append("&")
          .append("weidu=").append(weidu).append("&")
          .append("jingdu=").append(jingdu).append("&")
          .append("scanTime=").append(scanTime).append("&")
          // 闸机刷脸 用户信息
          .append("idCard=").append(idCard).append("&")
          .append("phone=").append(phone).append("&")
          .append("name=").append(URLEncoder.encode(name, "utf-8")).append("&")
          .append("identityName=").append(URLEncoder.encode(identityName, "utf-8")).append("&")
          .append("codeType=").append("work").append("&")
          .append("registerType=2").append("&")
          // 必填参数
          .append("shizheng=0").append("&")
          .append("direction=1").append("&")
          .append("isNormal=1").append("&")
          .append("identity=1").append("&")
          .append("address=");
    } catch (UnsupportedEncodingException e) {
      log.info("BladeGuardApi URLEncoder encode exception:{}", e.getMessage());
    }
    HttpPost httpPost = new HttpPost(apiUrl + "/blade-guard/wechat/scanHealthCode");
    //添加请求头
    httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
    //设置接收形式
    httpPost.setHeader("Accept", "application/json");
    //设置授权
    httpPost.setHeader("Blade-Auth", "bearer " + getAccessTokenTest());
    httpPost.setHeader("Authorization", "Basic c2FiZXI6c2FiZXJfc2VjcmV0");
    //创建登录实体
    httpPost.setEntity(new StringEntity(params.toString(), Charset.forName("UTF-8")));
    log.info("BladeGuardApi scanHealthCode req:{}", httpPost);
    String str = HttpClientUtil.doPost(httpPost);
    log.info("BladeGuardApi scanHealthCode res:" + str);
    JSONObject result = JSONObject.parseObject(str);
    if (null == result || StringUtils.isEmpty(result.getString("code"))) {
      return false;
    }
    String code = result.getString("code");
    if ("200".equals(code)) {
      return true;
    }
    return false;
  }

  private static Boolean scanHealthCodeTest(String userId, String projectID, String weidu,
      String jingdu, String idCard, String name, String identityName)
      throws UnsupportedEncodingException {
    String scanTime = "";
    Date date = new Date();
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    scanTime = dateFormat.format(date);
//    String params = String
//        .format("userId=%s&direction=1&registerType=2&isNormal=1&identity=1&weidu=%s&identityName=%E5%BB%BA%E7%AD%91%E5%B7%A5%E4%BA%BA&codeType=work&jingdu=%s&scanTime=%s&name=%E4%B8%A5%E6%B3%BD%E5%AE%87&shizheng=0&projectAddress=%E6%B1%9F%E6%B1%89%E5%8C%BA%E4%B8%AD%E5%A4%AE%E5%95%86%E5%8A%A1%E5%8C%BA%E4%B8%9C%E5%8C%97%E8%A7%92%EF%BC%8C%E9%9D%92%E5%B9%B4%E8%B7%AF%E5%92%8C%E5%B8%B8%E9%9D%92%E8%B7%AF%E4%BA%A4%E6%B1%87%E5%A4%84%E8%A5%BF%E5%8D%97%E5%A4%84&projectName=%E6%AD%A6%E6%B1%89%E5%B9%BF%E7%94%B5%E5%85%A8%E5%AA%92%E4%BD%93%E4%B8%AD%E5%BF%83%E8%AE%BE%E8%AE%A1%E5%8F%8A%E6%96%BD%E5%B7%A5%E6%80%BB%E6%89%BF%E5%8C%85%EF%BC%88EPC%EF%BC%89&projectId=%s&address=&idCard=420606199208023536&phone=13164618483",
//            "1533652988175904770",
//            "30.592762044270835",
//            "114.25089463975695",
//            scanTime,
//            "1439140329088871912");
    StringBuilder params = new StringBuilder();
    // 闸机信息
    params.append("userId=").append("1533652988175904770").append("&")
        .append("projectId=").append("1439140329088871912").append("&")
//        .append("projectAddress=").append(URLEncoder.encode("江汉区中央商务区东北角，青年路和常青路交汇处西南处","utf-8")).append("&")
//        .append("projectName=").append(URLEncoder.encode("武汉广电全媒体中心设计及施工总承包（EPC）","utf-8")).append("&")
        .append("weidu=").append("30.592762044270835").append("&")
        .append("jingdu=").append("114.25089463975695").append("&")
        .append("scanTime=").append(scanTime).append("&")
        // 闸机刷脸 用户信息
        .append("idCard=").append("420606199208023536").append("&")
//        .append("phone=").append("13164618483").append("&")
        .append("name=").append(URLEncoder.encode("严泽宇", "utf-8")).append("&")
        .append("identityName=").append(URLEncoder.encode("建筑工人", "utf-8")).append("&")
        .append("codeType=").append("work").append("&")
        .append("registerType=2").append("&")
        // 必填参数
        .append("shizheng=0").append("&")
        .append("direction=1").append("&")
        .append("isNormal=1").append("&")
        .append("identity=1").append("&")
        .append("address=");
    HttpPost httpPost = new HttpPost(
        "https://www.whcjj.com/api" + "/blade-guard/wechat/scanHealthCode");
    //添加请求头
    httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
    //设置接收形式
    httpPost.setHeader("Accept", "application/json");
    //设置授权
    httpPost.setHeader("Blade-Auth", "bearer " + getAccessTokenTest());
    httpPost.setHeader("Authorization", "Basic c2FiZXI6c2FiZXJfc2VjcmV0");
    //创建登录实体
    httpPost.setEntity(new StringEntity(params.toString(), Charset.forName("UTF-8")));
    log.info("BladeGuardApi request:{}", httpPost);
    String str = HttpClientUtil.doPost(httpPost);
    log.info("BladeGuardApi getAccessToken:" + str);
    JSONObject result = JSONObject.parseObject(str);
    if (null == result || StringUtils.isEmpty(result.getString("code"))) {
      return false;
    }
    String code = result.getString("code");
    if ("200".equals(code)) {
      return true;
    }
    return false;
  }

  /**
   * 获取Token
   */
  private static String getAccessTokenTest() {
    String params = String
        .format("username=%s&password=%s&tenantId=%s&grant_type=password&scope=all&type=account",
            "guard",
            "e10adc3949ba59abbe56e057f20f883e", "000000");
    HttpPost httpPost = new HttpPost("https://www.whcjj.com/api" + "/blade-auth//oauth/token");
    //添加请求头
    httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
    //设置接收形式
    httpPost.setHeader("Accept", "application/json");
    //设置租户id
    httpPost.setHeader("Tenant-Id", "000000");
    //设置授权
    httpPost.setHeader("Authorization", "Basic c2FiZXI6c2FiZXJfc2VjcmV0");
    //创建登录实体
    httpPost.setEntity(new StringEntity(params, Charset.forName("UTF-8")));
    log.info("BladeGuardApi request:{}", httpPost);
    String str = HttpClientUtil.doPost(httpPost);
    log.info("BladeGuardApi getAccessToken:" + str);
    JSONObject result = JSONObject.parseObject(str);
    if (null == result || StringUtils.isEmpty(result.getString("access_token"))) {
      return "";
    }
    return result.getString("access_token");
  }

  public static void main(String[] args) {
    try {
      System.out.println(scanHealthCodeTest(null, null, null, null, null, null, null));
    } catch (Exception e) {

    }
  }

}
